package com.hg.util.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;

class ActionJspInvoker{

    public void invoke(String view,HttpServletRequest req,HttpServletResponse res) {
        for (Enumeration<String> attrs = req.getAttributeNames(); attrs.hasMoreElements(); ) {
            String key = attrs.nextElement();
            Object value = req.getAttribute(key);
            req.setAttribute(key, handleObject(value, 5));
        }

        try
		{
			req.getRequestDispatcher(view).forward(req, res);
		}
		catch (ServletException | IOException e)
		{
			e.printStackTrace();
		}
    }

    private Object handleObject(Object value, int depth) {
        if (value == null || (depth--) <= 0)
            return value;
        if (value instanceof List)
            return handleList((List) value, depth);
        else if (value instanceof Map)
            return handleMap((Map) value, depth);
        else if (value instanceof Object[])
            return handleArray((Object[]) value, depth);
        else
            return value;
    }

    private Map handleMap(Map map, int depth) {
        if (map == null || map.size() == 0)
            return map;
        Map<Object, Object> result = new HashMap<Object, Object>();//2.4及之前版本也不区分大小写是不正确的
        for (Object eo : map.entrySet()) {
            Map.Entry<Object, Object> e = (Map.Entry) eo;
            Object key = e.getKey();
            Object value = e.getValue();
            value = handleObject(value, depth);
            result.put(key, value);
        }
        return result;
    }

    private List handleList(List list, int depth) {
        if (list == null || list.size() == 0)
            return list;
        List result = new ArrayList(list.size());
        for (Object value : list)
            result.add(handleObject(value, depth));
        return result;
    }
    private List handleArray(Object[] array, int depth) {
        if (array == null || array.length == 0)
            return new ArrayList(0);

        List result = new ArrayList(array.length);
        for (Object anArray : array) result.add(handleObject(anArray, depth));
        return result;
    }
}
